package com.weilive.push.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.weilive.push.gate.PusherServlet;
import com.weilive.push.service.apns.ApnsPusher;
import com.weilive.push.service.umeng.UmengPuser;

/**
 * 推送任务
 * 
 * @author houzhiwei
 *
 */
public class PushTask implements Runnable {
	private static final Logger logger = LoggerFactory.getLogger(PusherServlet.class);

	private static final String TOKEN_TYPE_IOS = "0";
	private static final String TOKEN_TYPE_ANDROID = "1";

	private static final int EXPIRE_TIME = 1;

	private String msg;// 消息
	private long userId;
	private Set<String> tokens;// token

	public PushTask(String msg, long userId, Set<String> tokens) {
		this.msg = msg;
		this.userId = userId;
		this.tokens = tokens;
	}

	public PushTask(String msg, Set<String> tokens) {
		this.msg = msg;
		this.tokens = tokens;
	}

	@Override
	public void run() {
		if (tokens == null || tokens.isEmpty()) {
			return;
		}
		long start = System.currentTimeMillis();
		logger.warn(Thread.currentThread().getName() + "正在执行。。。");
		// ios推送列表
		List<String> iosSend = new ArrayList<String>();
		// android推送列表
		List<List<String>> androidSend = new ArrayList<List<String>>();

		List<String> array = new ArrayList<String>();

		// 初始化
		androidSend.add(array);

		int iosCount = 0;
		int androidCount = 0;

		for (String s : tokens) {
			if (array.size() == 450) {
				array = new ArrayList<String>();
				androidSend.add(array);
			}
			String[] str = s.split(":");
			if (str.length != 2) {
				continue;
			}

			String type = str[0];
			String t = str[1];

			if (type.equals(TOKEN_TYPE_IOS)) {
				iosSend.add(t);
				iosCount++;
			} else if (type.equals(TOKEN_TYPE_ANDROID)) {
				array.add(t);
				androidCount++;
			}
		}

		logger.warn("处理ios推送={},android推送={}", new Object[] { iosCount, androidCount });

		try {
			if (iosSend.size() > 0) {
				ApnsPusher.APNSPush(iosSend, msg, userId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (androidSend.size() > 0) {
				// 450 * 4以内用列播
				if (androidSend.size() <= 4) {
					// 列播
					for (List<String> list : androidSend) {
						if(!list.isEmpty()){
							UmengPuser.AndroidListcast(list, msg, userId, EXPIRE_TIME);
						}
					}
					logger.info("umeng列广播了--!");
				} else {
					StringBuffer contentBuffer = new StringBuffer();
					for (List<String> list : androidSend) {
						for (String token : list) {
							contentBuffer.append(token);
							contentBuffer.append("\n");
						}
					}
					UmengPuser.AndroidFilecast(contentBuffer.toString(), msg, userId, EXPIRE_TIME);
					logger.info("umeng文件广播了--!");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.warn(Thread.currentThread().getName() + "执行完毕。。。 耗时ms=" + (System.currentTimeMillis() - start));
	}
}
